﻿<!DOCTYPE>
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=EDGE;IE=11;IE=8,chrome=1" />
    <title>排产结果调整</title>
    <link rel="stylesheet" type="text/css" href="/InSiteWebApplication/Content/AnyGantt/css/anychart-ui.min.css" />
    <link rel="stylesheet" type="text/css" href="/InSiteWebApplication/Content/AnyGantt/fonts/css/anychart-font.min.css" />
    <link href="/InSiteWebApplication/Content/Easyui/themes/metro/easyui.css" rel="stylesheet" />
    <link href="/InSiteWebApplication/Content/Easyui/custom-easyui.css" rel="stylesheet" />
    <link href="/InSiteWebApplication/Content/Easyui/themes/icon.css" rel="stylesheet" />
    <style type="text/css">
        .anychart-credits
        {
            display: none;
        }
    </style>
</head>
<body>
    <div class="panelSection">
        <div class="easyui-panel " title="查询区域" style="padding: 3px;width: 100%" data-options="closable:false,collapsible:true,minimizable:false,maximizable:false">
            <form id="searchForm" method="post" style="margin-bottom: 0;">
            <table>
                <tr class="divLabel">
                    <td>
                        订单号:
                    </td>
                    <td>
                        发动机号:
                    </td>
                    <td>
                        任务单号:
                    </td>
                    <td>
                        计划开始时间
                    </td>
                    <td>
                    </td>
                    <td>
                        计划结束时间
                    </td>
                    <td>
                    </td>
                    <td>
                    </td>
                </tr>
                <tr>
                    <td>
                        <input id="txtMfgorderName" class="easyui-textbox" name="MfgorderName" type="text"
                            style="width: 120px; height: 22px" />
                    </td>
                    <td>
                        <input id="txtMachine" class="easyui-textbox" name="Machine" type="text" style="width: 120px;
                            height: 22px" />
                    </td>
                    <td>
                        <input id="txtContainerNo" class="easyui-textbox" name="ContainerNo" type="text"
                            style="width: 120px; height: 22px" />
                    </td>
                    <!--<td><input  type="hidden" name="MFGORDERID" style="width:150px; height:22px;display:none"  id="MFGORDERID"/><div id="mfgCombox"></div></td>-->
                    <!--<td><input class="easyui-combobox" type="text" name="ContainerNo" style="width: 170px; height: 22px" id="ContainerNo" data-options="multiple:true"/></td>-->
                    <td>
                        <input id="txtPlanStartTime" type="text" name="PlanStartTime" class="easyui-datebox"
                            style="width: 110px; height: 22px" />
                    </td>
                    <td>
                        -
                    </td>
                    <td>
                        <input id="txtPlanEndTime" type="text" name="PlanEndTime" class="easyui-datebox"
                            style="width: 110px; height: 22px" />
                    </td>
                    <td>
                        <a href="javascript:void(0)" class="easyui-linkbutton linkbutton" onclick="page.searchData()">
                            查询</a>
                    </td>
                    <td>
                        <a href="javascript:void(0)" class="easyui-linkbutton linkbutton" onclick="page.searchReset()">
                            重置</a>
                    </td>
                    <td>
                    </td>
                </tr>
            </table>
            </form>
        </div>
    </div>
    <div class="panelSection">
        <div class="easyui-panel " title="排产结果信息" style="padding: 3px;width: 100%" data-options="closable:false,collapsible:true,minimizable:false,maximizable:false">
            <div id="container">
            </div>
        </div>
    </div>
    <div class="panelSection">
        <div class="easyui-panel " title="按钮区域" style="padding: 3px;width: 100%" data-options="closable:false,collapsible:true,minimizable:false,maximizable:false">
            <div style="margin: 15px 0px">
                <a href="javascript:void(0)" class="easyui-linkbutton linkbutton" onclick="page.saveAdjustedResult()">
                    保存调整</a> <a href="javascript:void(0)" class="easyui-linkbutton linkbutton" onclick="page.confirmAdjustedResult()">
                        确认</a>
            </div>
        </div>
    </div>
    <!--信息提示区域-->
    <div id="statusMessage" style="font-size: 14px; height: 40px">
    </div>
</body>
</html>
<script src="/InSiteWebApplication/Scripts/CustomPageJs/ReferenceJsLib.js" type="text/javascript"></script>
<script src="/InSiteWebApplication/Content/Easyui/jquery.min.js" type="text/javascript"></script>
<script src="/InSiteWebApplication/Content/Easyui/jquery.easyui.min.js" type="text/javascript"></script>
<script src="/InSiteWebApplication/Content/Easyui/easyui-lang-zh_CN.js" type="text/javascript"></script>
<script src="/InSiteWebApplication/Scripts/CustomPageJs/CustomCommon.js" type="text/javascript"></script>
<script type="text/javascript" src="/InSiteWebApplication/Content/AnyGantt/zh-cn.js"></script>
<script type="text/javascript" src="/InSiteWebApplication/Content/AnyGantt/anychart-base.min.js"></script>
<script type="text/javascript" src="/InSiteWebApplication/Content/AnyGantt/anychart-ui.min.js"></script>
<script type="text/javascript" src="/InSiteWebApplication/Content/AnyGantt/anychart-exports.min.js"></script>
<script type="text/javascript" src="/InSiteWebApplication/Content/AnyGantt/anychart-gantt.min.js"></script>
<script type="text/javascript" src="/InSiteWebApplication/Content/AnyGantt/anychart-data-adapter.min.js"></script>
<script type="text/javascript">
    var page = {
        parentID:'',//父窗体div
        rootPath: getRootPath(), //网站根路径
        ajaxUrl: getRootPath() + "/Ashx/ApsHandler/ZSLimitedCapacityHandler.ashx",
        param: [], //需要查看的id
        comboxUrl:getRootPath() + "/Ashx/ZsHandler/ZSTestRunNoticeBillHandler.ashx",//combox下拉-调用后台的URL
        comboxAction:"GetMfgorder",//combox下拉-调用后台的具体方法
        //初始化页面
        init: function () {
            page.bind();
        },
        bind:function(){
//    
        },
        movediffer:0,
        moveenddiffer:0,
        treeData:null,
        returnData:null,
        ContainerData:null,//任务单数据
        
        drawingFunction:function () {
              // get the shapes of the element
              var shapes = this["shapes"];
              // get the shape to be modified
              var path = shapes["path"];
              // get the bounds of the element
              var bounds = this["predictedBounds"];
    
            //this["period"];//当前渲染的块
            var item=this["item"];
            if(item.numChildren()>0){
               // console.log(this.period); 
                //path.fill('green');   
            }
              var h = bounds.height;
              var t = bounds.top;
              var l = bounds.left;
              var r = l + bounds.width;
              var h1 = t + h;   
  
            let period=this['period'];
            let customData=period.customData;
            if(customData!=null){

            //console.log(customData);

            if(customData.isHolidate!=null){

            h1+=4;
            t-=3;
            path.fill('#ccc');   
            //console.log(this['period']);

            }

            }
              path.moveTo(l, t);
              path.lineTo(l , h1 );
              path.lineTo(r, h1);
              path.lineTo(r, t);
              path.close(); 
},
        //保存调整后的结果
        saveAdjustedResult:function(){
            var apsCons=[];
            var adjustData=page.returnData.forEach(function(item){
               if( item.parent==null&&item.customData.differ!=0){
                    apsCons.push({
                        apsPlanInfoID:item.id,
                        STARTTIME:item.customData.constarttime,
                        ENDTIME:item.customData.conendtime,
                        type:'c'
                    })
               }
               if( item.parent!=null&&item.differ!=0){
                    apsCons.push({
                        apsPlanInfoID:item.id,
                        STARTTIME:item.periods[0].start,
                        ENDTIME:item.periods[0].end,
                        type:'s'
                    })
               }

            });

            if(apsCons.length==0){
                 displayMessage("未调整计划", false);
                return;
            }

            //console.log(page.returnData);
            var param = {
                action: "adjustInfiniteAps",
                conAps: JSON.stringify(apsCons)
            };
            $.ajax({
                type: "Post",
                url: page.ajaxUrl,
                data: param,
                cashe: false,
                async: true,
                beforeSend: function () {
                      $.messager.progress({ text: '', msg: '处理中...' });
                },
                success: function (data) {
                     $.messager.progress('close');
                    var result = JSON.parse(data);
                    if (result.Result) { 
                         page.loadInfiniteCapacity();                   
                         displayMessage("调整成功", true);
                    } else {
                        displayMessage(result.Message, false);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                     $.messager.progress('close');
                    alert(XMLHttpRequest.responseText);
                }
            });
        },
        confirmAdjustedResult:function(){
             var param = {
                    action: "confirmAdjustedResult",
                    data:JSON.stringify(page.ContainerData),
                    status:'2'
                }
             page.post(param, function (res) {
                if(res.Result)
                {
                    displayMessage("确认成功", true);
                    page.searchData();
                }
                displayMessage(res.Message, res.Result);
            });
        },       
        searchData:function(){
            page.reset(false,true,false);
            var ContainerNo= $('#txtContainerNo').textbox('getValue');           
            page.param=ContainerNo;            
            page.loadInfiniteCapacity();
        },
        searchReset:function(){
            page.reset(true,true,false);
        },
        loadInfiniteCapacity: function () { //无限产能加载方法
            $('#container').empty();
            anychart.onDocumentReady(function () {

                anychart.data.loadJsonFile(page.ajaxUrl + "?action=getStepInfiniteAps&machine="+$('#txtMachine').textbox('getValue')+"&containerNo="+$('#txtContainerNo').textbox('getValue')+"&mfgorderName="+$('#txtMfgorderName').textbox('getValue')+"&planStartTime="+$("#txtPlanStartTime").datebox('getValue')+"&planEndTime="+$("#txtPlanEndTime").datebox('getValue')+"&status=0", function (result) {

                    anychart.format.outputLocale('zh-cn');
                    //anychart.format.outputDateTimeFormat('yyyy-MM-dd');
                    anychart.format.inputDateTimeFormat("yyyy/MM/dd HH:mm:ss");

                    if(result.Result==false){
                        displayMessage(result.Message, false);
                        return;
                    }

                    var data=JSON.parse(result.ReturnData);
                    page.returnData=JSON.parse(result.ReturnData);
                    page.ContainerData=result.DBTable;
                    //console.log(data);

                    // create data tree on raw data
                    var treeData = anychart.data.tree(data, 'as-table');

                    page.treeData=treeData;
                    // create resource gantt chart
                    chart = anychart.ganttResource();

                    chart.splitterPosition(400); //左边grid宽度

                    // set data for the chart
                    chart.data(treeData);

                    //设置列
                    var dataGrid = chart.dataGrid();
                    dataGrid.column(0)
                            .title('序号')
                            .width(30)
                            .cellTextSettings({ hAlign: 'center' });

                    dataGrid.column(1)
                            .title("任务")
                            .cellTextSettingsOverrider(page.labelTextSettingsOverrider)
                            .cellTextSettings({ hAlign: 'left', width: 180 });

                    dataGrid.column(2)
                            .title("开始时间")
                            .cellTextSettings({ hAlign: 'left', width: 100 })
                            .format(item=>{
                                let customData=item.get("customData");                              
                                if(customData!=null)
                                 {
                                    return customData.constarttime;
                                  }
                                  else{
                                      var _periods=item.get('periods');
                                     var gridEnd="";
                                     _periods.forEach(function(i){
                                        gridEnd+=dayjs(i.start).format("YYYY/MM/DD HH:mm");//i.end.substr(0,i.start.lastIndexOf(":"))+ "\r\n";
                                     });
                                     return gridEnd;
                                  }
                            });
                    dataGrid.column(3)
                            .title("结束时间")
                            .cellTextSettings({ hAlign: 'left', width: 100 })
                            .format(item=>{
                                 let customData=item.get("customData");
                                  if(customData!=null)
                                 {
                                    return customData.conendtime;
                                  }
                                  else{
                                      var _periods=item.get('periods');
                                     var gridEnd="";
                                     _periods.forEach(function(i){
                                        gridEnd+=dayjs(i.end).format("YYYY/MM/DD HH:mm");//i.end.substr(0,i.end.lastIndexOf(":"))+ "\r\n";
                                     });
                                     return gridEnd;
                                  }                                
                            });
                     dataGrid.column(4)
                            .title("工位")
                            .cellTextSettings({ hAlign: 'left', width: 100 })
                            .format(item=>{
                                 let customData=item.get("customData");
                                 if(customData==null)
                                 {
                                     var _periods=item.get('periods');
                                     var gridEnd="";
                                     _periods.forEach(function(i){
                                        gridEnd+=i.workstation+ "\r\n";
                                     });
                                     return gridEnd;
                                  }                           
                            });
                     //datagrid tooltips
                    dataGrid.tooltip().useHtml(true); 

                    var periods = chart.getTimeline().periods();

                    // set the height of periods
                    //periods.height(40);
                    // draw custom periods
                    periods.rendering().drawer(page.drawingFunction);

                    //图形块的label
                    var periodLabels =periods.labels();
                    periodLabels.enabled(true);
                    periodLabels.useHtml(true);
                    periodLabels.fontColor("#104d89");
                    periodLabels.fontWeight(600);
                    periodLabels.format(function() {
                        let customData=this.period.customData;
                        if(customData!=null){
                            if(customData.isHolidate!=null&&customData.isHolidate=='1'){
                                var text='<span style="color:#fff;font-wieght:bold">'+this.period.text+'</span>';
                                return text;     
                            }
                        }
                    });

                    // configure tooltips of the timeline
                chart.getTimeline().tooltip().useHtml(true);
                chart.getTimeline().tooltip().format(function() {

                      var period=this.period;
                      var numChildren = this.item.numChildren();

                      var startDate = anychart.format.dateTime(this.start, "yyyy-MM-dd HH:mm:ss");
                      var endDate = anychart.format.dateTime(this.end, "yyyy-MM-dd HH:mm:ss");


                      var parentText ="<span style='font-weight:600;font-size:12pt'>" + 
                                     '开始:'+startDate + "<br>"+
                                     '结束:'+endDate+"</span>"

                      var childText ="<span style='font-weight:600;font-size:12pt'>" + 
                                     '开始:'+startDate + "<br>"+
                                     '结束:'+endDate+"</span>"

                     
                      // identify the resource type and display the corresponding text
                      if (numChildren > 0) {
                        //console.log(this.item.getChildAt(0).get('periods'));
                        return parentText;
                      } else {
                        //console.log(this.item.get('periods'));
                        return childText;
                      }

                });

                    // make chart editable
                    //chart.editing(true);
                    chart.getTimeline().edit(true);

                    chart.contextMenu(false);//禁用右键

                    // set container id for the chart
                    chart.container('container');

                    // initiate chart drawing
                    chart.draw();
                                       
                    // zoom chart all dates range
                    chart.fitAll();

                    // Enable chart redrawing.
                    chart.autoRedraw(true);
                                       

                    //事件绑定
                    treeData.listen('treeItemUpdate', function (e) {
                    console.info(e);
                        var val = e['value'];
                        var date=new Date(val);//移动后的日期

                        date=dayjs(anychart.format.dateTime(date,"yyyy-MM-dd HH:mm:ss")).set('second', 0);

                        var item=e['item'];
                        var parentItem=item.getParent();
                        if(parentItem==null)
                            return;
                        var allChildItems=parentItem.getChildren();
                        var preItem=page.returnData.find(i=>{return i.id==item.get('id')}) ;//调整之前的值
                        //var preDate=dayjs(preItem.periods[e['path'][1]].start);
                        var differ=0;
                        var path=e['path'][2];
                        if (path=='start'){
                         differ=dayjs(date).diff(dayjs(preItem.periods[e['path'][1]].start));
                         page.movediffer=differ;
                         console.info(path+"---------"+dayjs(date).format("YYYY/MM/DD HH:mm:ss")+"--------"+preItem.periods[e['path'][1]].start+"----"+differ);
                        }else if (path=='end'){     
                          differ=dayjs(date).diff(dayjs(preItem.periods[e['path'][1]].end));  
                          page.moveenddiffer=  differ;                
                          console.info(path+"---------"+dayjs(date).format("YYYY/MM/DD HH:mm:ss")+"------"+preItem.periods[e['path'][1]].end+"-----"+differ);
                        }
                        if(path=='end'){
                            if(page.movediffer== page.moveenddiffer){
                                page.recountApsData(parentItem.get('id'),item.get('id'),differ,"");
                            }else{
                                page.recountApsData(parentItem.get('id'),item.get('id'),page.movediffer!=0?page.movediffer:page.moveenddiffer,page.movediffer!=0?"p":"n");
                            }
                        }

//                        if(differ!=0&&page.movediffer!= page.moveenddiffer){
//                           page.recountApsData(parentItem.get('id'),item.get('id'),differ,path=="start"?"p":"n");
//                        }else{
//                            if(path=='end'){
//                                 //page.recountApsData(parentItem.get('id'),item.get('id'),differ,"");
//                            }
//                        }

                    });
                });
            });
        },
        recountApsData:function(parentId,itemId,differ,movetype){
        var data=page.returnData;
        var number=data.find(i=>{return i.id==itemId}).number; //修改的哪到工序
        for(var i=0;i<data.length;i++)
        {
            var item=data[i];
            if(item.number<number){continue;}
            if(item.parent==parentId)//工序级计划
                {
                    if(movetype=="p"){
                        item.periods[0].start=dayjs(item.periods[0].start).add(differ,'ms').format("YYYY/MM/DD HH:mm:ss");
                    }else if(movetype=="n"){
                        if(itemId==item.id){
                            item.periods[0].end=dayjs(item.periods[0].end).add(differ,'ms').format("YYYY/MM/DD HH:mm:ss");
                        }else{
                            item.periods[0].start=dayjs(item.periods[0].start).add(differ,'ms').format("YYYY/MM/DD HH:mm:ss");
                            item.periods[0].end=dayjs(item.periods[0].end).add(differ,'ms').format("YYYY/MM/DD HH:mm:ss");
                        }
                    }else{
                        item.periods[0].start=dayjs(item.periods[0].start).add(differ,'ms').format("YYYY/MM/DD HH:mm:ss");
                        item.periods[0].end=dayjs(item.periods[0].end).add(differ,'ms').format("YYYY/MM/DD HH:mm:ss");
                    }
                    //更新treeData
                    var treeItem= page.treeData.filter(_treeItem=>{
                        return _treeItem.get('id')==item.id;
                    });
                    if(treeItem!=null){

                       var prePeriods=treeItem[0].get('periods');
                       prePeriods[0].start=item.periods[0].start;
                       prePeriods[0].end=item.periods[0].end;
                       treeItem[0].set('periods',prePeriods);

                    }
                    item.differ=differ;
                    if(itemId==item.id&&movetype=="p"){
                        break;
                    }
                }
        }
        var stepData=data.filter(i=>{return i.parent==parentId});//所有工序信息
        var containerData=data.find(i=>{return i.id==parentId});//批次级信息
        var minStartdate=null;
        var maxEndDate=null;
            $.each(stepData,function(index,item){
                if(index==0){
                    minStartdate=item.periods[0].start;
                    maxEndDate=item.periods[0].end;
                }else{
                    if(dayjs(minStartdate)>dayjs(item.periods[0].start)){
                        minStartdate=item.periods[0].start;
                    }
                     if(dayjs(maxEndDate)<dayjs(item.periods[0].end)){
                        maxEndDate=item.periods[0].end;
                    }
                }
            });
                    containerData.periods[0].start=minStartdate;
                    containerData.periods[0].end=maxEndDate;
                    containerData.customData.differ=differ;
                    containerData.customData.constarttime=minStartdate;
                    containerData.customData.conendtime=maxEndDate;
                    //更新treeData
                    var treeItem= page.treeData.filter(_treeItem=>{
                        return _treeItem.get('id')==parentId;
                    });
                    if(treeItem!=null){
                       var prePeriods=treeItem[0].get('periods');
                       prePeriods[0].start=containerData.periods[0].start;
                       prePeriods[0].end=containerData.periods[0].end;
                       treeItem[0].set('periods',prePeriods);
                       treeItem[0].get('customData').differ=differ;
                       //console.log(treeItem);
                    }
        },
        labelTextSettingsOverrider:function(label, item) {
//               if(item.na.name.indexOf('正排')>0){
//                label.fontColor('red');
//                },

                var _periods=item.get('periods');               
                _periods.forEach(function(i){
                if(i.showcolor=="1")
                {
                    label.fontColor('red');                    
                }

                if(i.showcolor=="2")
                {
                    label.fontColor('yellow');                    
                }
                });           
        } ,
        //post数据
        post: function (param, callback) {
            $.ajax({
                type: "Post",
                url: page.ajaxUrl,
                data: param,
                cashe: false,
                async: true,
                dataType: "json",
                beforeSend: function () {
                    $.messager.progress({ text: '', msg: '处理中...' });
                },
                success: function (data) {
                    $.messager.progress('close');
                    callback(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $.messager.progress('close');
                    displayMessage(XMLHttpRequest.responseText, false);
                }
            });
        },
         //清除方法，重要！！！
    reset: function (iscondition, isresult, isDetail) {
        clearMessage();
        if (iscondition) {            
            $("#txtPlanStartTime").textbox("setValue", ""); 
            $("#txtPlanEndTime").textbox("setValue", ""); 
            $("#txtMfgorderName").textbox("setValue", ""); 
            $("#txtMachine").textbox("setValue", ""); 
            $("#txtContainerNo").textbox("setValue", ""); 
        }

        if (isresult) {
           $("#container").empty();
        }
    }
 }

$(function () {
    //获取传参
    page.parentID = getParam("parentDiv");
    page.param=[];//parent.$("#" + page.parentID).dialog('options').popupData;
    page.init();

});
</script>
<script src="/InSiteWebApplication/Scripts/ZsJs/selectCombox.js" type="text/javascript"></script>
